
<template>
  <div class="app-container">
    <el-row class="_head">
      <el-col :span="8">
        打印机服务状态：{{printSocketOpen?'连接':'未连接'}}
      </el-col>
      <el-col :span="8">
        <el-select v-model="usbSelectPrinter" size="mini" placeholder="请选择打印机">
          <el-option v-for="(item,name) in usbPrinters" :key="name" :value="name" :label="name" >

          </el-option>
        </el-select>
        <el-button
          size="mini"
          type="info" plain
          @click="getPrinters"
        >扫描设备</el-button>

      </el-col>
      <el-col :span="8">
        打印机连接状态：{{onlineUsbBool ?'连接':'未连接' }}
        <el-button
          size="mini"
          type="info" plain
          @click="selectOnLineUsbPrinter"
        >连接打印机</el-button>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-row :gutter="20">
      <el-col :span="4" :xs="24" v-if="isAdmin()">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="this.span" :xs="24" v-if="deptId != 0 && deptId != 100">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="煎药锅管理" name="first">
            <medicinal-pan :dept-id="this.deptId" @print="print"></medicinal-pan>
          </el-tab-pane>
          <el-tab-pane label="容器管理" name="second"><container :dept-id="this.deptId" @print="print"/></el-tab-pane>
          <el-tab-pane label="员工管理" name="third"><employee :dept-id="this.deptId"/></el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import employee from "./employee.vue";
import container from "./container.vue";
import medicinalPan from "./medicinalPan.vue";
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import user from "@/store/modules/user";
import Socket from "@/utils/Socket";
import NMPrintSocket from "@/utils/Print";
import Operlog from "@/views/monitor/operlog/index.vue";
import {qrCodePrintData} from "@/utils/printData/QrCode";

export default {
  components:{Operlog, employee,container,medicinalPan,Treeselect},
  data() {
    return {
      deptName: undefined,
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      activeName: 'first',
      deptId: 0,
      span:20,

      // 打印机相关
      // 打印服务是否连接成功
      printSocketOpen: false,
      usbSelectPrinter:"",
      usbPrinters: {},
      nMPrintSocket: null,
      onlineUsbBool:false,
      initSDKBool: false,
      selectedPrint:""
    };
  },
  watch:{
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },

  created(){
    this.getDeptTree();
    if(!this.isAdmin()){
      this.span = 24;
      this.deptId = this.$store.getters.deptId
    }
    this.initPrinter();
  },

  methods: {
    async initPrinter(){
      console.log("initPrinter");
      const socketData = new Socket("ws://127.0.0.1:37989");
      socketData.open(
        (openBool) => {
          console.log(openBool)
          this.printSocketOpen = openBool;
          console.log("开始调用获取打印机方法");
          this.getPrinters();
        },
        (msg) => {
          if (msg.resultAck.callback != undefined) {
            const callbackName = msg.resultAck.callback.name;
            const msgInfo = msg.resultAck.info;
            if (callbackName == "onCoverStatusChange") {
              //盒盖状态：0-闭合、1-打开
              console.log("盒盖状态", msgInfo.capStatus);
            } else if (callbackName == "onElectricityChange") {
              //"power" : 0-4, // 电池电量等级（共5档）
              console.log("电池电量等级", msgInfo.power);
            }

          }
        }
      );
      // 创建打印实例
      this.nMPrintSocket = new NMPrintSocket(socketData);
    },
    async getPrinters() {
      if (!this.printSocketOpen) {
        return this.$modal.msgWarning("打印服务未开启");
      }
      console.log("开始获取打印机");
      try {
        const allPrintersRes = await this.nMPrintSocket.getAllPrinters();
        if (allPrintersRes.resultAck.errorCode === 0) {
          const allPrinters = JSON.parse(allPrintersRes.resultAck.info);
          this.usbPrinters = { ...allPrinters };
          this.usbSelectPrinter = Object.keys(this.usbPrinters)[0];

          console.log(Object.keys(allPrinters)[0]);
          console.log(parseInt(this.usbPrinters[this.usbSelectPrinter]))


          this.selectOnLineUsbPrinter();
        } else {
          this.$modal.msgWarning("没有在线的打印机");
        }
      } catch (err) {
        console.error("getPrinters", err);
      }
    }
    ,
    // 连接打印机
    async selectOnLineUsbPrinter() {
      if (!this.printSocketOpen) {
        return this.$modal.msgWarning("打印服务未开启");
      }
      console.log("开始连接打印机");
      try {
        console.log(this.usbSelectPrinter)
        console.log(parseInt(this.usbPrinters[this.usbSelectPrinter]))
        const res = await this.nMPrintSocket.selectPrinter(
          this.usbSelectPrinter,
          parseInt(this.usbPrinters[this.usbSelectPrinter])
        );
        console.log(res.resultAck.errorCode);

        if (res.resultAck.errorCode === 0) {
          console.log("连接成功");
          this.onlineUsbBool = true;
          console.log("开始初始化SDK");
          this.initSDK();
        } else {

          console.log("连接失败");
          this.onlineUsbBool = false;
          this.$modal.msgWarning("连接失败");
        }
      } catch (err) {
        console.log("链接异常", err);
      }
    },
    //初始化SDK
    async initSDK() {
      if (!this.printSocketOpen) return this.$modal.msgWarning("打印服务未开启");

      try {
        const res = await this.nMPrintSocket.initSdk({ fontDir: "" });
        if (res.resultAck.errorCode == 0) {
          console.log("初始化成功");
          this.initSDKBool = true;
        } else {
          console.log("初始化失败");
          this.initSDKBool = false;
        }
      } catch (err) {
        console.error(err);
      }
    },

    async print(content){
      console.log(content)
      // let c = {type : 'pan', id : item.id, name: item.panName}
      let jsonString = JSON.stringify(content);


      if(!this.printSocketOpen) return this.$modal.msgWarning("打印服务位开启");
      // 打印浓度、 纸张类型、 打印模式、 总打印份数
      // 纸张类型 1. 间隙纸
      const startRes = await this.nMPrintSocket.startJob(
        3,1, 1, 1
      );

      if (startRes.resultAck.errorCode == 0) {
        // 提交打印任务
        //设置画布尺寸
        console.log("画布：", qrCodePrintData.InitDrawingBoardParam);
        const res = await this.nMPrintSocket.InitDrawingBoard(
          {
            width: 30,
            height: 50,
            rotate: 90,
            path: "ZT001.ttf",
            verticalShift: 0,
            HorizontalShift: 0,
          }
        )
        if (res.resultAck.errorCode != 0) {
          console.log("设置画布失败")
          return;
        }

        // 绘制元素
        const r = await this.nMPrintSocket.DrawLableQrCode({
          x:3,
          y:15,
          height:25,
          width:25,
          value:jsonString,
          rotate:0,
          codeType:31
        });
        if(r.resultAck.result != 0) {
          console.log("绘制元素失败")
          return
        } else {
          console.log("绘制二维码成功")
        }
        const r1 = await this.nMPrintSocket.DrawLableText({
          x:0,
          y:6,
          width: 30,
          rotate:0,
          fontSize: 5.0,
          textAlignHorizonral:1,
          path:"ZT001,ttf",
          value:content.name,
        })
        if(r1.resultAck.result != 0) {
          console.log("绘制元素失败")
          return
        } else {
          console.log("绘制文字成功")
        }

        const jsonObj = {
          printerImageProcessingInfo:{
            printQuantity:2
          },
        };
        const commitRes = await this.nMPrintSocket.commitJob(
          null,
          JSON.stringify(jsonObj)
        );
        console.log(commitRes);
        if (
          commitRes.resultAck.printQuantity == jsonObj.printerImageProcessingInfo.printQuantity &&
          commitRes.resultAck.onPrintPageCompleted ==
          this.jsonObj.printerImageProcessingInfo.printQuantity
        ) {
          //结束打印任务
          const endRes = await this.nMPrintSocket.endJob();
          console.log(endRes);
          if (endRes.resultAck.errorCode === 0) {
            console.log("打印完成");
          }
          return;
        }

        if (commitRes.resultAck.errorCode === 0){
          // this.$modal.msgWarning("end")
        }


      }
    },

    isAdmin(){
      let roles = this.$store.getters.roles;
      for(let i=0;i<roles.length;i++){
        if(roles[i] == 'admin'){
          return true;
        }
      }
      return false;
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.deptId = data.id;
      console.log(this.deptId);
    },
  }
};
</script>

<style>
._head{
  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

}
.el-divider--horizontal {

  margin: 2px 0;
}
</style>
